package com.java.springtest.mvc;

import com.java.springtest.mvc.controller.SimpleController;
import com.java.springtest.mvc.handler.AnnotationHandlerAdapter;
import com.java.springtest.mvc.handler.HttpHandlerAdapter;
import com.java.springtest.mvc.handler.SimpleHandlerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Woo_home
 * @create by 2020/2/18
 */
public class DispatchServlet {

    public static List<HandlerAdapter> handlerAdapters = new ArrayList<>();

    public DispatchServlet() {
        handlerAdapters.add(new HttpHandlerAdapter());
        handlerAdapters.add(new SimpleHandlerAdapter());
        handlerAdapters.add(new AnnotationHandlerAdapter());
    }

    public void doDispatch() {
        // 此处模拟 SpringMVC 从 request 获取 handler 的对象
        // 适配器可以获取到想要的 Controller
        //AnnotationController controller = new AnnotationController();
        //HttpController controller = new HttpController();
        SimpleController controller = new SimpleController();

        // 得到对象的适配器
        HandlerAdapter adapter = getHandler(controller);

        // 通过适配器执行对应的 Controller 方法
        adapter.handle(controller);
    }

    public HandlerAdapter getHandler(Controller controller) {
        // 遍历根据得到的 controller（handler）返回对应的适配器
        for (HandlerAdapter handlerAdapter : handlerAdapters) {
            if (handlerAdapter.supports(controller)) {
                return handlerAdapter;
            }
        }
        return null;
    }
}
